<?php
//---------------配置-------------------
define("APPID", "wxeb31508256b4ce1a");
define("APPSECRET", "be8d49ed8ad2a409cf5a8c0875b460a1");
define("REDIRECT_URI", urlencode("http://shuaiphp.com/8-personTest2.php"));
define("SCOPE", "snsapi_userinfo");//定义获取用户基本信息，还是获取用户信息
define("STATE", "nouse_shuai");
//--------------------封装成一个类----------
class WeChat {
	private $_appid;
	private $_appsecret;
	private $_token;
	public function __construct($appid, $appsecret=null, $token=null) {
		$this -> _appid = $appid;
		$this -> _appsecret = $appsecret;
		$this -> _token = $token;
	}

	//get或者post请求
	public function _request($url, $https = true, $method = 'get', $data = null) {
		$ch = curl_init();
		//初始化
		curl_setopt($ch, CURLOPT_URL, $url);
		//设置选项，包括URL
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		//只获取页面内容，不输出
		curl_setopt($ch, CURLOPT_HEADER, 0);
		//不输出头部信息
		if ($https) {
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			//不做服务器认证
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
			//不做客户端认证
		}
		if ($method == 'post') {
			curl_setopt($ch, CURLOPT_POST, true);
			//设置请求方式
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			//post请求数据
		}
		$output = curl_exec($ch);
		//执行并获取HTML文档内容
		curl_close($ch);
		//释放curl句柄
		//echo $output;//打印获得的数据
		return $output;
	}

	//获取基础accesstoken，具有过期自动获取功能
	public function _getAccesstoken() {
		$file = './accesstoken';
		if (file_exists($file)) {
			$content = file_get_contents($file);
			$content = json_decode($content);
			if (time() - filemtime($file) < $content -> expires_in) {
				return $content -> access_token;
			}
		}
		$content = $this -> _request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this -> _appid . "&secret=" . $this -> _appsecret);
		file_put_contents($file, $content);
		$content = json_decode($content);
		return $content -> access_token;
	}

	//由code获取网页授权accesstokend
	public function _getWebAccess($code) {
		$res = $this -> _request('https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this -> _appid . '&secret=' . $this -> _appsecret . '&code=' . $code . '&grant_type=authorization_code');
		$res = json_decode($res);
		//直接用刷新token
		$refresh_token = $res->refresh_token;
		$res = $this -> _request('https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$this->_appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
		$res = json_decode($res);
		return $res;
	}
	//根据页面access_token以及openid获取用户信息
	public function _getuserInfo($access_token,$openid){
//		$webAccess = $this->_getWebAccess($code);
//		$access_token = $webAccess->access_token;
//		$openid = $webAccess->openid;
		$res = $this->_request('https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN');
		$res = json_decode($res);
		return $res;
	}

}
